/*
Copyright 1990-2005 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#include <stdio.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <sys/stat.h>

#include "imbean.h"

#define ELEMENT_INITIAL_SIZE      6

#define IBML_ERR_STR_DEFAULT                     "IBML Parser Error"
#define IBML_ERR_STR_NO_MEMORY                   "IBML Error:  No Memory"
#define IBML_ERR_STR_INVALID_ELEMENT_NAME        "IBML Error:  Invalid Element Name"
#define IBML_ERR_STR_INVALID_ELEMENT_ATTRIBUTE   "IBML Error:  Invalid Element Property"
#define IBML_ERR_STR_INVALID_ELEMENT_ITEM        "IBML Error:  Invalid Element Item"

enum {
    IBML_ERR_OK = 0,
    IBML_ERR_NO_MEMORY,
    IBML_ERR_INVALID_ELEMENT_NAME,
    IBML_ERR_INVALID_ELEMENT_ATTRIBUTE,
    IBML_ERR_INVALID_ELEMENT_ITEM,
};

#define SafeFree(pointer)               if(pointer) free((char *)(pointer))

static IbmlProperty *ibml_property_new()
{
    IbmlProperty *ibml_property;

    ibml_property = (IbmlProperty *) malloc(sizeof(IbmlProperty));
    if (ibml_property == NULL)
	return NULL;

    ibml_property->name = NULL;
    ibml_property->type = NULL;
    ibml_property->value = NULL;
    ibml_property->options = NULL;
    ibml_property->scope = NULL;

    return ibml_property;
}

static int ibml_property_free(IbmlProperty * ibml_property)
{
    if (ibml_property == NULL)
	return IBML_OK;

    SafeFree(ibml_property->name);
    SafeFree(ibml_property->type);
    SafeFree(ibml_property->value);
    SafeFree(ibml_property->options);
    SafeFree(ibml_property->scope);

    SafeFree(ibml_property);

    return IBML_OK;
}

static int ibml_property_print(IbmlProperty * ibml_property)
{
    char *name;
    char *type;
    char *value;
    char *options;
    char *scope;

    if (ibml_property == NULL)
	return IBML_OK;

    name = ibml_property->name;
    type = ibml_property->type;
    value = ibml_property->value;
    options = ibml_property->options;
    scope = ibml_property->scope;
    if (name && value) {
	printf("    name: %s, value: %s,  ", name, value);
	if (type)
	    printf("type: %s  ", type);
	if (options)
	    printf("options: %s  ", options);
	if (scope)
	    printf("scope: %s  ", scope);
	printf("\n");
    }

    return IBML_OK;
}

static IbmlElement *ibml_element_new()
{
    IbmlElement *ibml_element;

    ibml_element = (IbmlElement *) malloc(sizeof(IbmlElement));
    if (ibml_element == NULL)
	return NULL;

    ibml_element->id = NULL;
    ibml_element->scope = NULL;
    ibml_element->class = NULL;

    ibml_element->num_properties = 0;
    ibml_element->properties = NULL;

    return ibml_element;
}

static int ibml_element_free(IbmlElement * ibml_element)
{
    int i;

    if (ibml_element == NULL)
	return IBML_OK;

    SafeFree(ibml_element->id);
    SafeFree(ibml_element->scope);
    SafeFree(ibml_element->class);

    for (i = 0; i < ibml_element->num_properties; i++)
	ibml_property_free(ibml_element->properties[i]);
    SafeFree(ibml_element->properties);

    SafeFree(ibml_element);

    return IBML_OK;
}

static int ibml_element_print(IbmlElement * ibml_element)
{
    int i;
    char *id;

    if (ibml_element == NULL)
	return IBML_OK;

    id = ibml_element->id;
    if (id && *id)
	printf("  id: %s\n", id);

    for (i = 0; i < ibml_element->num_properties; i++)
	ibml_property_print(ibml_element->properties[i]);

    return IBML_OK;
}

static int ibml_element_pushback_property(IbmlElement * ibml_element,
                                          IbmlProperty * ibml_property)
{
    int i, num_properties;

    if (ibml_element == NULL || ibml_property == NULL)
        return IBML_ERROR;

    if (ibml_element->properties == NULL) {
        ibml_element->properties = (IbmlProperty **) calloc (ELEMENT_INITIAL_SIZE,
                                                             sizeof(IbmlProperty *));
        if (ibml_element->properties == NULL)
            return IBML_ERROR;
    }

    num_properties = ibml_element->num_properties;
    if ((num_properties + 1) % ELEMENT_INITIAL_SIZE == 0) {
        int num = num_properties + 1 + ELEMENT_INITIAL_SIZE;

        ibml_element->properties = (IbmlProperty **)realloc(ibml_element->properties,
                                                            num * sizeof(IbmlProperty *));
        if (ibml_element->properties == NULL)
            return IBML_ERROR;

        for (i = num_properties; i < num; i++)
            ibml_element->properties[i] = NULL;
    }

    ibml_element->properties[num_properties] = ibml_property;
    ibml_element->num_properties ++;

    return IBML_OK;
}

static IbmlCategory *ibml_category_new()
{
    IbmlCategory *ibml_category;

    ibml_category = (IbmlCategory *) malloc(sizeof(IbmlCategory));
    if (ibml_category == NULL)
	return NULL;

    ibml_category->num_elements = 0;
    ibml_category->elements = NULL;

    return ibml_category;
}

static int ibml_category_free(IbmlCategory * ibml_category)
{
    int i;

    if (ibml_category == NULL)
	return IBML_OK;

    for (i = 0; i < ibml_category->num_elements; i++)
	ibml_element_free(ibml_category->elements[i]);
    SafeFree(ibml_category->elements);

    SafeFree(ibml_category->scope);
    SafeFree(ibml_category);

    return IBML_OK;
}

static int ibml_category_print(IbmlCategory * ibml_category)
{
    int i;
    char *scope;

    if (ibml_category == NULL)
	return IBML_OK;

    scope = ibml_category->scope;
    if (scope && *scope)
	printf("Category: %s\n", scope);

    for (i = 0; i < ibml_category->num_elements; i++)
	ibml_element_print(ibml_category->elements[i]);

    return IBML_OK;
}

static int ibml_category_pushback_element(IbmlCategory * ibml_category,
                                          IbmlElement * ibml_element)
{
    int i, num_elements;

    if (ibml_category == NULL || ibml_element == NULL)
        return IBML_ERROR;

    if (ibml_category->elements == NULL) {
        ibml_category->elements = (IbmlElement **) calloc (ELEMENT_INITIAL_SIZE,
                                                           sizeof(IbmlElement *));
        if (ibml_category->elements == NULL)
            return IBML_ERROR;
    }

    num_elements = ibml_category->num_elements;
    if ((num_elements + 1) % ELEMENT_INITIAL_SIZE == 0) {
        int num = num_elements + 1 + ELEMENT_INITIAL_SIZE;

        ibml_category->elements = (IbmlElement **)realloc(ibml_category->elements,
                                                          num * sizeof(IbmlElement *));
        if (ibml_category->elements == NULL)
            return IBML_ERROR;

        for (i = num_elements; i < num; i++)
            ibml_category->elements[i] = NULL;
    }

    ibml_category->elements[num_elements] = ibml_element;
    ibml_category->num_elements ++;

    return IBML_OK;
}

IbmlData *ibml_data_new()
{
    IbmlData *ibml_data;

    ibml_data = (IbmlData *) malloc(sizeof(IbmlData));
    if (ibml_data == NULL)
	return NULL;

    ibml_data->num_categories = 0;
    ibml_data->categories = NULL;

    return ibml_data;
}

int ibml_data_free(IbmlData * ibml_data)
{
    int i;

    if (ibml_data == NULL)
	return IBML_OK;

    for (i = 0; i < ibml_data->num_categories; i++)
	ibml_category_free(ibml_data->categories[i]);
    SafeFree(ibml_data->categories);

    SafeFree(ibml_data);

    return IBML_OK;
}

int ibml_data_print(IbmlData * ibml_data)
{
    int i;

    if (ibml_data == NULL)
	return IBML_OK;

    for (i = 0; i < ibml_data->num_categories; i++)
	ibml_category_print(ibml_data->categories[i]);

    return IBML_OK;
}

static int ibml_data_pushback_category(IbmlData * ibml_data,
                                       IbmlCategory * ibml_category)
{
    int i, num_categories;

    if (ibml_data == NULL || ibml_category == NULL)
        return IBML_ERROR;

    if (ibml_data->categories == NULL) {
        ibml_data->categories = (IbmlCategory **) calloc (ELEMENT_INITIAL_SIZE,
                                                          sizeof(IbmlCategory *));
        if (ibml_data->categories == NULL)
            return IBML_ERROR;
    }

    num_categories = ibml_data->num_categories;
    if ((num_categories + 1) % ELEMENT_INITIAL_SIZE == 0) {
        int num = num_categories + 1 + ELEMENT_INITIAL_SIZE;

        ibml_data->categories = (IbmlCategory **)realloc(ibml_data->categories,
                                                         num * sizeof(IbmlCategory *));
        if (ibml_data->categories == NULL)
            return IBML_ERROR;

        for (i = num_categories; i < num; i++)
            ibml_data->categories[i] = NULL;
    }

    ibml_data->categories[num_categories] = ibml_category;
    ibml_data->num_categories ++;

    return IBML_OK;
}

static char *ibml_strdup(char *str)
{
    char *ptr;

    ptr = (char *) calloc(strlen(str) + 1, 1);
    if (ptr != NULL)
	strcpy(ptr, str);

    return ptr;
}

static char *get_error_message(int error_no)
{
    switch (error_no) {
    case IBML_ERR_NO_MEMORY:
	return IBML_ERR_STR_NO_MEMORY;
    case IBML_ERR_INVALID_ELEMENT_NAME:
	return IBML_ERR_STR_INVALID_ELEMENT_NAME;
    case IBML_ERR_INVALID_ELEMENT_ATTRIBUTE:
	return IBML_ERR_STR_INVALID_ELEMENT_ATTRIBUTE;
    case IBML_ERR_INVALID_ELEMENT_ITEM:
	return IBML_ERR_STR_INVALID_ELEMENT_ITEM;
    }
    return IBML_ERR_STR_DEFAULT;
}

int parseImbeanProperty(xmlDocPtr doc, xmlNodePtr cur,
			IbmlElement * ibml_element)
{
    xmlChar *property_name = NULL;
    xmlChar *property_value = NULL;
    xmlChar *property_scope = NULL;
    xmlChar *property_options = NULL;
    xmlChar *property_type = NULL;

    IbmlProperty *ibml_property;

    ibml_property = (IbmlProperty *) ibml_property_new();
    if (ibml_property == NULL) {
	return IBML_ERROR;
    }

    property_name = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_NAME);
    if (property_name && *property_name)
	ibml_property->name = (char *) ibml_strdup(property_name);
    xmlFree(property_name);

    property_value = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_VALUE);
    if (property_value && *property_value)
	ibml_property->value = (char *) ibml_strdup(property_value);
    xmlFree(property_value);

    property_options = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_OPTIONS);
    if (property_options && *property_options)
	ibml_property->options = (char *) ibml_strdup(property_options);
    xmlFree(property_options);

    property_type = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_TYPE);
    if (property_type && *property_type)
	ibml_property->type = (char *) ibml_strdup(property_type);
    xmlFree(property_type);

    property_scope = xmlGetProp(cur, IBML_ELEMENT_SCOPE);
    if (property_scope && *property_scope)
	ibml_property->scope = (char *) ibml_strdup(property_scope);
    xmlFree(property_scope);

    ibml_element_pushback_property(ibml_element, ibml_property);

    return IBML_OK;
}

int parseImbeanElement(xmlDocPtr doc, xmlNodePtr cur,
		       IbmlCategory * ibml_category)
{
    xmlChar *id = NULL;
    xmlChar *scope = NULL;

    IbmlElement *ibml_element;

    ibml_element = ibml_element_new();
    if (ibml_element == NULL)
	return IBML_ERROR;

    id = xmlGetProp(cur, IBML_ELEMENT_IMBEAN_ID);
    if (id && *id)
	ibml_element->id = (char *) ibml_strdup(id);
    xmlFree(id);

    scope = xmlGetProp(cur, IBML_ELEMENT_SCOPE);
    if (scope && *scope)
	ibml_element->scope = (char *) ibml_strdup(scope);
    xmlFree(scope);

    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
	if (!xmlStrcmp(cur->name, (const xmlChar *) IBML_ELEMENT_PROPERTY)) {
	    parseImbeanProperty(doc, cur, ibml_element);
	}
	cur = cur->next;
    }

    ibml_category_pushback_element(ibml_category, ibml_element);

    return IBML_OK;
}

int parseImCategory(xmlDocPtr doc, xmlNodePtr cur, IbmlData * ibml_data)
{
    xmlChar *scope;
    xmlChar *class;

    IbmlCategory *ibml_category;

    ibml_category = ibml_category_new();
    if (ibml_category == NULL)
	return IBML_ERROR;

    scope = xmlGetProp(cur, IBML_ELEMENT_SCOPE);
    if (scope && *scope)
	ibml_category->scope = (char *) ibml_strdup(scope);
    xmlFree(scope);

    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
	if (!xmlStrcmp(cur->name, (const xmlChar *) IBML_ELEMENT_IMBEAN)) {
	    parseImbeanElement(doc, cur, ibml_category);
	}
	cur = cur->next;
    }

    ibml_data_pushback_category(ibml_data, ibml_category);

    return IBML_OK;
}

IbmlData *imbean_config_new_from_memory(char *buffer, int size)
{
    xmlDocPtr doc;
    xmlNodePtr cur;

    IbmlData *ibml_data;

    doc = xmlParseMemory(buffer, size);
    if (doc == NULL)
	return NULL;

    cur = xmlDocGetRootElement(doc);
    if (cur == NULL) {
	xmlFreeDoc(doc);
	return NULL;
    }

    if (xmlStrcmp(cur->name, (xmlChar *) IBML_ELEMENT_ROOT)) {
	fprintf(stderr, "wrong root, should be %s\n", IBML_ELEMENT_ROOT);
	xmlFreeDoc(doc);
	return NULL;
    }

    ibml_data = ibml_data_new();
    if (ibml_data == NULL) {
	xmlFreeDoc(doc);
	return NULL;
    }

    cur = cur->xmlChildrenNode;
    while (cur) {
	if (!xmlStrcmp(cur->name, (const xmlChar *) IBML_ELEMENT_CATAGORY)) {
	    parseImCategory(doc, cur, ibml_data);
	}
	cur = cur->next;
    }

    xmlFreeDoc(doc);
    return ibml_data;
}

IbmlData *imbean_config_new_from_file(char *file_name)
{
    IbmlData *ibml_data;
    FILE *fd;

    struct stat file_stat;
    int file_size;
    char *base;

    if (stat(file_name, &file_stat) == -1)
	return NULL;

    file_size = file_stat.st_size;
    if (file_size == 0)
	return NULL;

    if ((fd = fopen(file_name, "r")) == NULL)
	return NULL;

    base = (char *) calloc(file_size, sizeof(char));
    if (base == NULL) {
	fclose(fd);
	return NULL;
    }

    if (fread((char *) base, sizeof(char), file_size, fd) != file_size) {
	free((char *) base);
	fclose(fd);
	return NULL;
    }

    ibml_data = (IbmlData *) imbean_config_new_from_memory(base, file_size);

    free((char *) base);
    fclose (fd);
    return ibml_data;
}
